// 应用程序的启动入口程序
const express = require('express');
const swig = require('swig');
const app = express();
const sequelize = require('./db')
const User = require('./schemas/users');
const bodyParser = require('body-parser')
const Cookies = require('cookies');

// 解决跨域问题
app.all('*', function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  // res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Access-Control-Expose-Headers", "over-line-error");
  next();
})

// 设置静态文件托管
app.use('/public', express.static(__dirname + '/public'));

// 配置模板
app.engine('html',  swig.renderFile);
// 设置模板的文件路径
app.set('views', './views');
app.set('view engine', 'html');
// 不缓存模板页面
swig.setDefaults({cache: false});

// 连接数据库
const main = async () => {
  // 尝试连接数据库
  try {
    await sequelize.authenticate();
    await sequelize.sync();// 同步所有模型
    console.log('Connection successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
};
main();
// bodyparser设置
app.use(bodyParser.urlencoded());
// 设置cookies
app.use(async function(req, res, next){
  req.cookies = new Cookies(req, res);

  req.userInfo = {};
  if(req.cookies.get('userInfo')){
    try {
      req.userInfo = JSON.parse(req.cookies.get('userInfo'));
      // 获取当前登录用户是否是管理员
      let resUser = await User.findByPk(req.userInfo.id);
      console.log(resUser);
      next();
    } catch (error) {
      console.log(error);
    }
  }else{
    next();
  }
})

// 根据不同的功能划分模块
app.use('/admin', require('./routers/admin'));
app.use('/api', require('./routers/api'));
app.use('/', require('./routers/main'));

app.listen(8081);
